const koa = require("koa");
const router = require('koa-router')();
const koaBody = require("koa-body");
const static = require("koa-static");
const fs = require("fs");
const path = require("path");
const app = new koa();
const main = require("./modules/index");

router.get("/find", async ctx => {
    var collection = await main();
    const result = await collection.find({}).toArray();
    ctx.body = result
})
router.get("/add", async ctx => {
    var collection = await main();
    var obj = {
        name: "张三",
        age: 17
    }
    // var res = await collection.insertOne(obj);
    var res = await collection.find({ name: obj.name }).toArray();
    if (res.length) {
        ctx.body = "数据库中已经有该值"
    } else {
        var result = await collection.insertOne(obj);
        console.log(result);
    }
})
router.post("/doForm", async ctx => {
    var { username, age } = ctx.request.body;
    age = Number(age);

    var fileName = ctx.request.files.logo.path;
    /**1.创建一个可读流 */
    var reader = fs.createReadStream(fileName);
    /**2.设置上传的文件名 */
    var upLoadFile = `./static/${path.basename(fileName)}`;
    /**3.创建一个可写流 */
    var writer = fs.createWriteStream(upLoadFile);
    /**4.通过管道将可读流写入可写流 */
    reader.pipe(writer);
    
    var logo = ctx.origin + "/" + path.basename(fileName);
    const collection = await main();
    await collection.insertOne({name:username,age,logo});
    await ctx.redirect("/find");
})

app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 20 * 1024 * 1024,
        keepExtensions: true
    }
}))
app.use(static(path.join(__dirname, "static")))
app.use(async (ctx, next) => {
    ctx.set("Access-Control-Allow-Origin", "*");
    await next();
})
app.use(router.routes())

app.listen(8080)